#ifndef PROTOCOLHANDLER_H
#define PROTOCOLHANDLER_H

#include <QObject>
#include <QByteArray>

// Protocol constants
constexpr quint16 FRAME_START_MARKER = 0xAAAA;
constexpr quint8 SOURCE_ID_DISPLAY = 0x01;

// Command definitions
enum class FocusCommand : quint8 {
    Invalid = 0x00,
    ManualFocusPlus = 0x01,
    ManualFocusMinus = 0x02,
    SetFocusValue = 0x03,
    Brake = 0x04,
    BrakeRelease = 0x05,
    AutoFocus = 0x06,
    Reset = 0x07
};

// Work status bit flags
struct WorkStatus {
    bool selfCheckPassed;    // Bit 0
    bool autoFocusMode;      // Bit 1
    bool brakeEngaged;       // Bit 3
    
    static WorkStatus fromByte(quint8 statusByte) {
        return {
            (statusByte & 0x01) != 0,
            (statusByte & 0x02) != 0,
            (statusByte & 0x08) != 0
        };
    }
};

class ProtocolHandler : public QObject
{
    Q_OBJECT
    
public:
    explicit ProtocolHandler(QObject *parent = nullptr);
    
    // Frame construction
    QByteArray buildCommandFrame(quint8 sourceId, quint8 destId, quint8 frameCounter,
                                  quint8 command, const QByteArray &params, quint16 imageClarity);
    
    // Frame parsing
    void processIncomingData(const QByteArray &data);
    
signals:
    void frameReceived(quint8 sourceId, quint8 command, quint8 workStatus,
                       qint16 currentStep, qint16 totalTravel);
    void frameError(const QString &error);
    
private:
    quint8 calculateChecksum(const QByteArray &data);
    bool validateFrame(const QByteArray &frame);
    void parseStatusFrame(const QByteArray &frame);
    
    QByteArray m_receiveBuffer;
};

#endif // PROTOCOLHANDLER_H
